
import java.net.InetAddress;
import java.net.UnknownHostException;

import hypeerweb.HyPeerWeb;
import hypeerweb.HyPeerWebProxy;

import communicator.GlobalObjectId;
import communicator.LocalObjectId;
import communicator.MachineAddress;
import communicator.ObjectDB;
import communicator.PeerCommunicator;
import communicator.PortNumber;

public class hypeerweblauncher
{
    private static ObjectDB db;
    public static void main (String[] args)
    {
        PortNumber port;
        try
        {
            port = new PortNumber(Integer.parseInt(args[0]));
        }
        catch(Exception e)
        {
            usage();
            return;
        }
        PortNumber.setApplicationsPortNumber(port);
        PeerCommunicator.createPeerCommunicator(port);
        String machineName = "mace";//this gets changed later
        try
        {
            machineName = InetAddress.getLocalHost().toString();
            machineName = machineName.split("/")[0];//grabs just our machine name to pass it over
        }
        catch (UnknownHostException e1)
        {
            e1.printStackTrace();
        }//the name of the computer that you are on
        MachineAddress.setMachineAddress(machineName);
        
        db = ObjectDB.getSingleton();
        
        HyPeerWeb hpw = HyPeerWeb.getSingleton();
        hpw.reload();
        GlobalObjectId globalId = hpw.get_GlobalId();
        
        if(args.length > 1)
        {
            if((args.length != 4) || (!args[1].equals("-m")))
            {
                usage();
                return;
            }
            String masterName = args[2];
            PortNumber masterPort;
            try
            {
                masterPort = new PortNumber(Integer.parseInt(args[3]));
            }
            catch(Exception e)
            {
                usage();
                return;
            }
            System.out.println("Master:");
            GlobalObjectId master = new GlobalObjectId(masterName, masterPort, 
                                                       new LocalObjectId(Integer.MIN_VALUE));
            hpw.setMaster(new HyPeerWebProxy(master));
        }
        
        db.store(globalId.getLocalObjectId(), hpw);
        System.out.println("HyPeerWeb v6.1.297");
        System.out.println("IP address: "+ globalId.getMachineAddr() + "\nPort number: " 
                + globalId.getPortNumber() + "\nLocal ID: " + globalId.getLocalObjectId() + "\n\n");
        PeerCommunicator.getSingleton().run();
    }
    
    public static void usage()
    {
        System.out.println("USAGE: port [-m machinename otherport]");
    }
}